package javase_class_250912;

/**
 * ClassName: StringTest2
 * Package: javase_class_250912
 * Description:
 *
 * @Author harkjeans
 * @Create 2025/9/12 9:25
 * @Version 1.0
 */
public class StringTest2 {
    public static void main(String[] args) {
        String s1 = "hello";// 来自常量池
        String s2 = "world";// 来自常量池
        String s3 = "hello" + "world";// 编译期优化，直接等于 "helloworld"，来自常量池
        String s4 = s1 + "world";// 运行期拼接，new StringBuilder().append(s1).append("world").toString()，在堆上创建新对象
        String s5 = s1 + s2;// 运行期拼接，new StringBuilder().append(s1).append(s2).toString()，在堆上创建新对象
        String s6 = (s1 + s2).intern();// 运行期拼接后，将结果放入常量池，并返回常量池的引用

        System.out.println("s1: " + System.identityHashCode(s1));
        System.out.println("s2: " + System.identityHashCode(s2));
        System.out.println("s3: " + System.identityHashCode(s3));
        System.out.println("s4: " + System.identityHashCode(s4));
        System.out.println("s5: " + System.identityHashCode(s5));
        System.out.println("s6: " + System.identityHashCode(s6));
//        s1: 1078694789
//        s2: 81628611
//        s3: 1828972342
//        s4: 1452126962
//        s5: 931919113
//        s6: 1828972342


        System.out.println(s3 == s4);//false
        System.out.println(s3 == s5);//false
        System.out.println(s4 == s5);//false
        System.out.println(s3 == s6);//true

    }

}
